package com.mall.service.impl;

import com.mall.common.BusinessException;
import com.mall.common.GlobalExceptionHandler;
import com.mall.common.PageResult;
import com.mall.dto.UserLoginDTO;
import com.mall.dto.UserRegisterDTO;
import com.mall.entity.User;
import com.mall.mapper.UserMapper;
import com.mall.service.UserService;
import com.mall.util.JwtUtil;
import com.mall.vo.UserInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    @Transactional
    public void register(UserRegisterDTO registerDTO) {
        // 检查用户名是否已存在
        if (userMapper.existsByUsername(registerDTO.getUsername())) {
            throw new BusinessException("用户名已存在");
        }
        // 检查手机号是否已存在
        if (userMapper.existsByPhone(registerDTO.getPhone())) {
            throw new BusinessException("手机号已被注册");
        }
        // 检查邮箱是否已存在
        if (StringUtils.hasText(registerDTO.getEmail()) && userMapper.existsByEmail(registerDTO.getEmail())) {
            throw new BusinessException("邮箱已存在");
        }

        User user = new User();
        BeanUtils.copyProperties(registerDTO, user);
        // 加密密码
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        // 设置默认值
        user.setUserType(1); // 普通用户
        user.setStatus(1); // 正常状态
        
        userMapper.insert(user);
    }
    @Override
    public UserInfoVO.LoginVO login(UserLoginDTO loginDTO) {
        User user = userMapper.selectByUsername(loginDTO.getUsername());
        if (user == null || !passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }
        if (user.getStatus() != 1) {
            throw new BusinessException("账号已被禁用");
        }

        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(user, userInfoVO);
        userInfoVO.setUserTypeDesc();
        userInfoVO.setStatusDesc();

        String token = jwtUtil.generateToken(user.getId(), user.getUsername()); //生成 Token

        return new UserInfoVO.LoginVO(token, userInfoVO);
    }

    @Override
    public void addUser(User user) {
        if (userMapper.existsByUsername(user.getUsername())) {
            throw new BusinessException("用户名已存在");
        }
        if (userMapper.existsByPhone(user.getPhone())) {
            throw new BusinessException("手机号已被注册");
        }
        if (StringUtils.hasText(user.getEmail()) && userMapper.existsByEmail(user.getEmail())) {
            throw new BusinessException("邮箱已存在");
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        if (user.getUserType() == null) user.setUserType(1);
        if (user.getStatus() == null) user.setStatus(1);
        userMapper.insert(user);
    }

    @Override
    public void updateUserByAdmin(Long userId, User user) {
        user.setId(userId);
        userMapper.updateById(user);
    }

    @Override
    public UserInfoVO getUserById(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) throw new BusinessException("用户不存在");
        UserInfoVO vo = new UserInfoVO();
        BeanUtils.copyProperties(user, vo);
        return vo;
    }

    @Override
    public List<UserInfoVO> listUsers(Integer pageNum, Integer pageSize, String keyword) {
        // 简单实现：返回所有用户（可根据实际分页/模糊查询实现）
        List<User> users = userMapper.selectAll(keyword);
        List<UserInfoVO> voList = new ArrayList<>();
        for (User user : users) {
            UserInfoVO vo = new UserInfoVO();
            BeanUtils.copyProperties(user, vo);
            voList.add(vo);
        }
        return voList;
    }

    @Override
    public UserInfoVO getUserInfo(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(user, userInfoVO);
        return userInfoVO;
    }

    @Override
    @Transactional
    public void updateUserInfo(Long userId, User updateUser) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 检查手机号是否被其他用户使用
        if (StringUtils.hasText(updateUser.getPhone()) && 
            !updateUser.getPhone().equals(user.getPhone()) && 
            userMapper.existsByPhone(updateUser.getPhone())) {
            throw new BusinessException("手机号已被使用");
        }
        
        // 检查邮箱是否被其他用户使用
        if (StringUtils.hasText(updateUser.getEmail()) && 
            !updateUser.getEmail().equals(user.getEmail()) && 
            userMapper.existsByEmail(updateUser.getEmail())) {
            throw new BusinessException("邮箱已被使用");
        }

        //将不可修改信息存回去
        updateUser.setId(userId);
        updateUser.setUsername(user.getUsername());
        updateUser.setPassword(user.getPassword());
        updateUser.setUserType(user.getUserType());
        updateUser.setStatus(user.getStatus());
        updateUser.setCreateTime(user.getCreateTime());
        updateUser.setUpdateTime(user.getUpdateTime());
        userMapper.updateById(updateUser);
    }

    @Override
    @Transactional
    public void changePassword(Long userId, String oldPassword, String newPassword) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            throw new BusinessException("原密码错误");
        }

        /**
         * 这里更新逻辑有问题
         * 不能只把待跟新的内容插回去，会导致用户信息丢失
         * */
        User updateUser = new User();
        BeanUtils.copyProperties(user, updateUser); //先保存原信息
        updateUser.setPassword(passwordEncoder.encode(newPassword)); //在更新信息
        userMapper.updateById(updateUser);
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public User getUserByPhone(String phone) {
        return userMapper.selectByPhone(phone);
    }

    @Override
    public boolean existsByUsername(String username) {
        return userMapper.existsByUsername(username);
    }

    @Override
    public boolean existsByPhone(String phone) {
        return userMapper.existsByPhone(phone);
    }

    @Override
    public boolean existsByEmail(String email) {
        return userMapper.existsByEmail(email);
    }

    @Override
    public PageResult<UserInfoVO> getUserPage(Integer pageNum, Integer pageSize, String keyword, Integer userType, Integer status) {
        int offset = (pageNum - 1) * pageSize;
        List<User> users = userMapper.selectPage(offset, pageSize, keyword, userType, status);
        Long total = userMapper.selectCount(keyword, userType, status);
    
        List<UserInfoVO> userInfoVOs = new ArrayList<>();
        for (User user : users) {
            UserInfoVO userInfoVO = new UserInfoVO();
            BeanUtils.copyProperties(user, userInfoVO);
            userInfoVO.setUserTypeDesc();
            userInfoVO.setStatusDesc();
            userInfoVOs.add(userInfoVO);
        }
        PageResult<UserInfoVO> pageResult = new PageResult<>();
        pageResult.setList(userInfoVOs);
        pageResult.setTotal(total);
        return pageResult;
    }
    

    @Override
    @Transactional
    public void updateUserStatus(Long userId, Integer status) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        userMapper.updateStatus(userId, status);
    }

    @Override
    @Transactional
    public void deleteUser(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        userMapper.deleteById(userId);
    }

    @Override
    @Transactional
    public void deleteUsers(Long[] userIds) {
        if (userIds != null && userIds.length > 0) {
            List<Long> idList = new ArrayList<>();
            for (Long userId : userIds) {
                idList.add(userId);
            }
            userMapper.deleteBatchByIds(idList);
        }
    }

    @Override
    @Transactional
    public String resetPassword(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 生成随机密码
        String newPassword = generateRandomPassword();
        
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setPassword(passwordEncoder.encode(newPassword));
        userMapper.updateById(updateUser);
        
        return newPassword;
    }
    
    /**
     * 生成随机密码
     */
    private String generateRandomPassword() {
        // 这里简单实现，实际应该更复杂
        return "123456";
    }
}